package od_2025A.one;


import java.util.*;

/**
 * https://blog.csdn.net/qq_45776114/article/details/146410561
 * todo 这道题重点把握以下几点：
 * 1、建模
 * 2、边界条件
 * 3、递归理解的还是不够，尤其是在递归后的return,是该把归并排序以及二叉树多遍历几遍了
 */
public class Test01 {

    static class FileInfo {

        private int length;

        private List<String> childFileInfoIds;

        public FileInfo(int length, List<String> childFileInfoIds) {
            this.length = length;
            this.childFileInfoIds = childFileInfoIds;
        }

    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] firstLine = scanner.nextLine().split(" ");
        int fileCount = Integer.parseInt(firstLine[0]);
        String goalFileInfoId = firstLine[1];

        Map<String, FileInfo> nodeMap = new HashMap<>(fileCount);
        for (int i = 0; i < fileCount; i++) {
            String[] lineContent = scanner.nextLine().split(" ");
            String substring = lineContent[2].substring(1, lineContent[2].length() - 1);
            String[] childFileInfoIds = substring.length() == 0 ? new String[]{} : substring.split(",");
            FileInfo fileInfo = new FileInfo(Integer.parseInt(lineContent[1]), Arrays.asList(childFileInfoIds));
            nodeMap.put(lineContent[0], fileInfo);
        }

        FileInfo fileInfo = nodeMap.get(goalFileInfoId);
        if (Objects.isNull(fileInfo)) {
            System.out.println(0);
        }

        int calculate = calculate(fileInfo, nodeMap);
        System.out.println(calculate);

    }

    private static int calculate(FileInfo fileInfo, Map<String, FileInfo> nodeMap) {
        int sum = fileInfo.length;
        List<String> childFileInfoIds = fileInfo.childFileInfoIds;
        if (childFileInfoIds == null || childFileInfoIds.isEmpty()) {
            return sum;
        }
        for (String childFileInfoId : childFileInfoIds) {
            sum += calculate(nodeMap.get(childFileInfoId), nodeMap);
        }
        return sum;
    }
}


